#include <avr/io.h>


#include "System.h"
#include "Pins.h"
#include "Buttons.h"

#define DEBOUNCE_COUNT	10


typedef struct {
	// Debounced State
	uint8_t		State;
	// State of the last button poll
	uint8_t		LastPoll;
	// Number of consecutive matches
	uint8_t		Count;	
	
	uint8_t		StateChanged;
	uint8_t		NewState;
} button_debounce_t;

static button_debounce_t Buttons[2];

static void button_debounce_init(button_debounce_t *btn)
{
	btn->State =0;
	btn->LastPoll=0;
	btn->Count=0;	
	btn->StateChanged=0;
	btn->NewState=0;	
}


void buttons_init(void)
{
	
	button_debounce_init(&Buttons[0]);
	button_debounce_init(&Buttons[1]);
	
	
	CLEAR_BIT(BUTTON1_DDR, BUTTON1);	//Set as input pin
	CLEAR_BIT(BUTTON2_DDR, BUTTON2);	//Set as input pin
	CLEAR_BIT(BUTTON3_DDR, BUTTON3); 	//Set as input pin
	CLEAR_BIT(BUTTON4_DDR, BUTTON4);	//Set as input pin	
	
}


static void poll_button(button_debounce_t *btn,
								uint8_t value)
{
	
	if (value) value=1;
	if (value == btn->LastPoll)
	{
		btn->Count=0;	
	} else  {
		btn->Count++;
		if (btn->Count >=DEBOUNCE_COUNT)
		{
			btn->Count=0;			
			btn->State = value;
			
			btn->NewState=value;
			btn->StateChanged=1;
		}		
	}	
	btn->LastPoll=value;	
}



void poll_buttons_ISR(void)
{
	poll_button(&Buttons[0],GET_BIT(BUTTON1_PINS,BUTTON1));	
	poll_button(&Buttons[1],GET_BIT(BUTTON2_PINS,BUTTON2));
	
	
}


void button_update(void)
{
	
	
	
}
